package com.zidongxiangxi.rabbit.producer.transaction.support;

import com.zidongxiangxi.rabbit.producer.entity.RabbitMessageInfo;

/**
 * 事务上下文
 *
 * @author chenxudong
 * @date 2020/11/07
 */
public class RabbitMessageTransactionContext {
	private static final ThreadLocal<RabbitMessageTransactionHolder> MESSAGE_HOLDER_THREAD_LOCAL =
			ThreadLocal.withInitial(RabbitMessageTransactionHolder::new);

	public static RabbitMessageTransactionHolder getMessageHolder() {
		return MESSAGE_HOLDER_THREAD_LOCAL.get();
	}

	public static void setMessageHolder(RabbitMessageTransactionHolder messageHolder) {
		MESSAGE_HOLDER_THREAD_LOCAL.set(messageHolder);
	}

	public static void removeMessageHolder() {
		MESSAGE_HOLDER_THREAD_LOCAL.remove();
	}

	public static void stashMessage(RabbitMessageInfo rabbitMessage) {
		RabbitMessageTransactionHolder messageHolder = getMessageHolder();
		if (messageHolder == null) {
			messageHolder = new RabbitMessageTransactionHolder();
			setMessageHolder(messageHolder);
		}
		messageHolder.add(rabbitMessage);
	}
}
